package cn.billho.popcache.starter.config;

import cn.billho.popcache.starter.config.properties.PopCacheProperties;
import cn.billho.popcache.starter.config.properties.PRedisProperties;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

@Configuration
@ComponentScan(basePackages = "cn.billho.popcache.starter.config.properties")
public class PRedisConfig {
    @Autowired
    PopCacheProperties popCacheProperties;

    @Bean(name = "popRedisConn")
    public StatefulRedisConnection<String,String> getStatefulConnection(){
        PRedisProperties PRedisProperties = popCacheProperties.getRedis();
        int port = (PRedisProperties.getPort());
        long timeout = (PRedisProperties.getTimeout());
        int database = (PRedisProperties.getDatabase());
        RedisURI redisUri = RedisURI.builder()                    // <1> 创建单机连接的连接信息
                .withHost(PRedisProperties.getHost())
                .withPort(port)
                .withTimeout(Duration.of(timeout, ChronoUnit.SECONDS))
                .withPassword(PRedisProperties.getPassword())
                .withDatabase(database)
                .build();
        RedisClient redisClient = RedisClient.create(redisUri);   // <2> 创建客户端
        StatefulRedisConnection<String, String> connection = redisClient.connect();     // <3> 创建线程安全的连接
        return connection;
    }

}
